<template>
  <div class="card msgManage">
    <div class="search">
      <el-input v-model="input" style="width: 240px" placeholder="请输入消息标题" @keyup.enter="search" />
      <div class="btns">
        <el-button type="danger" @click="search">搜索</el-button>
        <el-button type="primary" @click="add">新增</el-button>
      </div>
    </div>
    <div class="table-container">
      <stable style="margin-top: 10px" :columns="tableSetting.columns" :data="tableSetting.data"></stable>
    </div>
    <vxe-pager
      v-model:currentPage="page.currentPage"
      v-model:pageSize="page.pageSize"
      :total="page.total"
      @page-change="pageChange"
    >
    </vxe-pager>
    <!-- 查看附件抽屉 -->
    <el-drawer v-model="isShowDrawer" title="查看附件" :show-close="true" size="65%" direction="btt">
      <FullText ref="fulltextRef"></FullText>
    </el-drawer>
    <!-- 新增编辑弹出框 -->
    <el-dialog v-model="dialogFormVisible" :title="`${isEdit ? '编辑' : '新增'}`" width="600">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item label="消息标题" :label-width="formLabelWidth" prop="MDI_Title">
          <el-input v-model="form.MDI_Title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="消息内容" :label-width="formLabelWidth" prop="MDI_Content">
          <el-input v-model="form.MDI_Content" autocomplete="off" />
        </el-form-item>
        <el-form-item label="消息链接" :label-width="formLabelWidth">
          <el-input v-model="form.MDI_Url" autocomplete="off" />
        </el-form-item>
        <el-form-item label="消息权限" :label-width="formLabelWidth">
          <el-input v-model="form.MDI_UsersID" autocomplete="off" />
        </el-form-item>
        <el-form-item label="消息创建者" :label-width="formLabelWidth">
          <el-input v-model="form.MDI_Create_By" autocomplete="off" />
        </el-form-item>
        <el-form-item label="消息类型" :label-width="formLabelWidth" prop="MDI_Type">
          <el-select v-model="form.MDI_Type" placeholder="请选择消息类型">
            <el-option label="内部" value="内部" />
            <el-option label="行业" value="行业" />
            <el-option label="政策" value="政策" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息备注" :label-width="formLabelWidth">
          <el-input v-model="form.MDI_Remark" :rows="3" type="textarea" autocomplete="off" />
        </el-form-item>
        <el-form-item label="是否启用" :label-width="formLabelWidth">
          <el-checkbox v-model="form.MDI_Enable" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="msgManage">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import FullText from "../dynamicMain/components/FullText/FullText.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { getCurTime } from "@/utils/formatter";
import { useCatalogStore } from "@/stores/modules/catalog";
import { ButtonStatus } from "../dynamicMain/components/TopBar/InitButton";

interface PageChangeParams {
  pageSize: number;
  currentPage: number;
}

const { proxy } = useCurrentInstance();

const input = ref("");
const ruleFormRef = ref<FormInstance>();
// 弹框状态
const dialogFormVisible = ref(false);
// label宽度
const formLabelWidth = "100px";
// 是否是编辑
const isEdit = ref<boolean>(false);
// 点击的当前行
const curRow = ref<any>();
// 点击显示附件内容
const isShowDrawer = ref<boolean>(false);

// 获取全文组件实例
const fulltextRef = ref();

// 按钮状态实例
const buttonStatus = new ButtonStatus();
const catalogStore = useCatalogStore();

// 分页配置
const page = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

let form = ref({
  MDI_Title: "",
  MDI_Content: "",
  MDI_Url: "",
  MDI_UsersID: "",
  MDI_Enable: true,
  MDI_Create_By: "",
  MDI_Type: "",
  MDI_Remark: ""
});

// 表格配置
const tableSetting = reactive({
  columns: [
    { field: "MDI_No", title: "序号", width: 70 },
    { field: "MDI_Create_Time", title: "创建时间", sortable: true },
    { field: "MDI_Title", title: "消息标题", sortable: true },
    { field: "MDI_Content", title: "消息内容", sortable: true },
    { field: "MDI_Url", title: "消息链接", sortable: true },
    { field: "MDI_UsersID", title: "消息权限", sortable: true },
    {
      field: "MDI_Enable",
      title: "是否启用",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return row.MDI_Enable ? "是" : "否";
        }
      }
    },
    { field: "MDI_Create_By", title: "消息创建者", sortable: true },
    { field: "MDI_Type", title: "消息类型", sortable: true },
    { field: "MDI_Remark", title: "消息备注", sortable: true },
    {
      title: "操作",
      width: 180,
      align: "center",
      slots: {
        default: ({ row }: any) => {
          return (
            <div>
              <el-button type="primary" link onClick={() => edit(row)}>
                编辑
              </el-button>
              <el-button type="danger" link onClick={() => del(row)}>
                删除
              </el-button>
              <el-button type="warning" link onClick={() => showFile(row)}>
                附件
              </el-button>
            </div>
          );
        }
      }
    }
  ],
  data: []
});

const rules = reactive<FormRules>({
  MDI_Title: [{ required: true, message: "请输入消息标题", trigger: "blur" }],
  MDI_Content: [{ required: true, message: "请输入消息内容", trigger: "blur" }],
  MDI_Type: [
    {
      required: true,
      message: "请选择消息类型",
      trigger: "change"
    }
  ]
});

// 分页调用
const pageChange = ({ pageSize, currentPage }: PageChangeParams) => {
  page.currentPage = currentPage;
  page.pageSize = pageSize;
  getMsgs();
};

// 搜索
const search = () => {
  if (!input.value) {
    getMsgs();
    return;
  }
  tableSetting.data = tableSetting.data.filter((item: any) => item.MDI_Title.includes(input.value));
};

// 查看附件;
const showFile = (row: any) => {
  console.log("查看附件", row);
  row.Record_ID = row.MDI_ID;
  row.FM_ID = "";
  row.FMT_ID = "";
  isShowDrawer.value = true;
  nextTick(() => {
    fulltextRef.value.getData(row);
  });
  buttonStatus.filterFulltextButtonAuth(JSON.parse(catalogStore.treeNode.PC_PermissionStr)[1]);
};

// 删除消息
const del = (row: any) => {
  console.log(row);
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.post("/Master_Base_MsgDocInfo/Delete", [row.MDI_ID]).then((res: any) => {
        console.log(res);
        getMsgs();
      });
    });
};

// 添加消息
const addMsg = () => {
  if (isEdit.value) {
    proxy.$vueAxios
      .put("/Master_Base_MsgDocInfo", {
        MDI_ID: curRow.value.MDI_ID,
        ...form.value,
        MDI_Create_Time: getCurTime()
      })
      .then((res: any) => {
        res.Mark && getMsgs();
      });
  } else {
    proxy.$vueAxios
      .post("/Master_Base_MsgDocInfo", {
        MDI_ID: proxy.$global.createID(),
        ...form.value,
        MDI_Create_Time: getCurTime()
      })
      .then((res: any) => {
        res.Mark && getMsgs();
      });
  }
};

// 获取消息
const getMsgs = () => {
  proxy.$vueAxios
    .get("/Master_Base_MsgDocInfo/Get", {
      order: "MDI_Order asc",
      pageIndex: page.currentPage,
      pageSize: page.pageSize
    })
    .then((res: any) => {
      console.log(res);
      res.List.forEach((item: any, index: number) => {
        item.MDI_No = index + 1;
      });
      tableSetting.data = res.List;
      page.total = res.Count;
    });
};

// 展示添加/修改弹窗
const add = () => {
  isEdit.value = false;
  form.value.MDI_Title = "";
  form.value.MDI_Content = "";
  form.value.MDI_Url = "";
  form.value.MDI_UsersID = "";
  form.value.MDI_Enable = false;
  form.value.MDI_Create_By = "";
  form.value.MDI_Type = "";
  form.value.MDI_Remark = "";
  dialogFormVisible.value = true; // 弹出新增框
};

// 确认添加消息
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogFormVisible.value = false;
      addMsg();
    } else {
    }
  });
};

// 编辑消息
const edit = (row: any) => {
  console.log(row);
  isEdit.value = true;
  curRow.value = row;
  dialogFormVisible.value = true;
  proxy.$vueAxios.get("/Master_Base_MsgDocInfo/GetById", { objId: row.MDI_ID }).then((res: any) => {
    if (res.Mark) {
      form.value = res.Model;
    }
  });
};

onMounted(() => {
  getMsgs();
});
</script>

<style lang="scss" scoped>
.msgManage {
  height: 100%;
  .search {
    display: flex;
    .btns {
      margin-left: 20px;
    }
  }
  .table-container {
    height: calc(100% - 90px);
  }
}
</style>
